<template>
  <div class="page">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button
              class="back-btn"
              :icon="ArrowLeft"
              @click="handleBack">返回</el-button>
            <el-button
              class="add-btn"
              type="primary"
              @click="openDialog('add', null)">新增学生</el-button>
            <div class="info-group">
              <span class="total-count">共计{{ total }}条</span>
              <span class="class-name">{{ clazzDetailStore.clazz_name }}</span>
            </div>
          </div>
          <div class="right">
            <el-form inline @submit.prevent>
              <el-form-item label="姓名">
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入姓名"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item label="学号">
                <el-input
                  v-model="searchForm.student_num"
                  placeholder="请输入学号"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="Search"
                  @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="clientData"
        style="width: 100%"
        empty-text="暂无数据"
        :table-layout="tableLayout">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="student_num" label="学号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="sex_display" label="性别" />
        <el-table-column prop="clazz_name" label="班级名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="180">
          <template #default="data">
            <div class="icon-group">
              <el-tooltip effect="light" content="编辑" placement="top">
                <el-button
                  icon="Edit"
                  type="primary"
                  @click="openDialog('edit', data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="查看成绩" placement="top">
                <el-button
                  icon="View"
                  type="warning"
                  @click="handleView(data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="删除" placement="top">
                <el-button
                  icon="Delete"
                  type="danger"
                  @click="handleDelete(data.row.id)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        background
        layout="total,  prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </el-card>
    <el-dialog v-model="dialogVisible" :title="dialogFormTitle">
      <el-form ref="formRef" :model="dialogForm">
        <el-form-item label="学号" label-width="140px" prop="student_num">
          <el-input v-model="dialogForm.student_num" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" label-width="140px" prop="name">
          <el-input v-model="dialogForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="年龄" label-width="140px" prop="age">
          <el-input v-model="dialogForm.age" autocomplete="off" type="number" />
        </el-form-item>
        <el-form-item label="描述" label-width="140px" prop="description">
          <el-input
            v-model="dialogForm.description"
            autocomplete="off"
            type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(dialogFormTitle === '新增学生' ? 'add' : 'edit')">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useClazzDetailStore } from '../../stores/clazz'
import { useStudentDetailStore } from '../../stores/student'
import { addStudent, deleteStudent, updateStudent } from '../../api/student'
const clazzDetailStore = useClazzDetailStore()
const studentDetailStore = useStudentDetailStore()
const router = useRouter()
import { useDepartmentStore } from '../../stores/department'
const departmentStore = useDepartmentStore()
// 总条数
const total = ref(0)
// 表格布局
const tableLayout = ref('fixed')
// 表格当前的显示数据
const clientData = ref([])
// 存储所有数据用于本地分页
const allData = ref([])
// 当前页数
const current = ref(1)
// 每页的显示条数
const pageSize = ref(10)
// 表格加载状态
const loading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)

// 搜索相关
const searchForm = reactive({
  name: '',
  student_num: ''
})

// 对话框标题
const dialogFormTitle = ref('')
// 对话框表单数据
const dialogForm = reactive({
  id: null,
  student_num: '',
  name: '',
  age: '',
  description: '',
  clazz: clazzDetailStore.clazz_id,
  department: departmentStore.department_id
})

// 表单元素
const formRef = ref(null)

// 获取班级ID
const clazz_id = computed(() => clazzDetailStore.clazz_id)

// 加载数据方法
const loadData = async () => {
  loading.value = true
  try {
    // 获取班级详情，包含学生列表
    const res = await clazzDetailStore.getClazzDetailPinia(clazz_id.value)
    if (res.success) {
      // 从API响应中提取学生数据
      allData.value = res.data.students || []
      applyLocalSearchAndPagination()
    } else {
      ElMessage.error(res.error || '获取班级详情失败')
    }
    loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage.error(error.message || '获取班级详情失败')
  }
}

// 本地搜索和分页函数
const applyLocalSearchAndPagination = () => {
  let filteredData = allData.value

  // 本地搜索过滤
  if (searchForm.name.trim()) {
    filteredData = filteredData.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  if (searchForm.student_num.trim()) {
    filteredData = filteredData.filter((item) =>
      item.student_num
        .toLowerCase()
        .includes(searchForm.student_num.toLowerCase())
    )
  }

  // 设置总数
  total.value = filteredData.length

  // 本地分页
  const start = (current.value - 1) * pageSize.value
  const end = start + pageSize.value
  clientData.value = filteredData.slice(start, end)
}

const handleCurrentChange = (value) => {
  current.value = value
  applyLocalSearchAndPagination()
}

const handleSizeChange = (value) => {
  pageSize.value = value
  current.value = 1
  applyLocalSearchAndPagination()
}

// 搜索处理函数
const handleSearch = () => {
  current.value = 1 // 搜索时重置到第一页
  applyLocalSearchAndPagination()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.student_num = ''
  current.value = 1
  applyLocalSearchAndPagination()
}

// 返回处理函数
const handleBack = () => {
  router.push('/students')
}

// 删除处理函数
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条学生数据吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用API删除学生
    await deleteStudent(id)

    // 从本地数据中删除
    const index = allData.value.findIndex((item) => item.id === id)
    if (index > -1) {
      allData.value.splice(index, 1)
    }

    // 智能分页处理 - 当删除当前页最后一条数据时，自动跳转到上一页
    if (current.value > 1 && clientData.value.length === 1) {
      current.value--
    }

    ElMessage.success('删除成功!')

    // 重新应用本地搜索和分页
    applyLocalSearchAndPagination()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('删除操作已取消')
    } else {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 打开对话框
const openDialog = (model, id) => {
  dialogFormTitle.value = model === 'add' ? '新增学生' : '编辑学生'
  dialogForm.id = id
  if (model === 'add') {
    dialogForm.student_num = ''
    dialogForm.name = ''
    dialogForm.age = ''
    dialogForm.description = ''
    dialogForm.clazz = clazz_id.value
    dialogForm.department = departmentStore.department_id
  } else {
    // 编辑模式，根据ID从本地数据中查找并填充表单
    const item = allData.value.find((item) => item.id === id)
    if (item) {
      dialogForm.student_num = item.student_num
      dialogForm.name = item.name
      dialogForm.age = item.age
      dialogForm.description = item.description
    }
  }
  dialogVisible.value = true
}

const submitForm = async (model) => {
  try {
    await formRef.value.validate()
    if (model === 'add') {
      await addStudent(dialogForm)
      // 新增成功后，刷新数据
      loadData()
    } else {
      // 编辑学生逻辑
      await updateStudent(dialogForm.id, dialogForm)
    }
    ElMessage.success('操作成功!')
    dialogVisible.value = false
    // 刷新数据
    loadData()
    applyLocalSearchAndPagination()
  } catch (error) {
    ElMessage.error(error.message || '操作失败，请重试')
  }
}
const handleView = (id) => {
  studentDetailStore.setStudentId(id)
  router.push('/studentsDetail')
}
onMounted(() => {
  if (clazz_id.value) {
    loadData()
  } else {
    ElMessage.warning('未选择班级，请从班级管理页面进入')
    router.push('/students')
  }
})
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    gap: 15px;

    .info-group {
        display: flex;
        align-items: center;
        gap: 8px;

        .total-count {
          font-size: 0.7rem;
          font-weight: 500;
          color: #606266;
          background: #f5f7fa;
          padding: 2px 8px;
          border-radius: 2px;
        }

        .class-name {
          font-size: 0.7rem;
          font-weight: 500;
          color: #606266;
          background: #f0f9ff;
          padding: 2px 8px;
          border-radius: 2px;
        }
      }
  }

  .right {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.icon-group {
  display: flex;
  gap: 8px;

  .el-button {
    padding: 4px 8px;
  }
}
</style>
